# -*- coding: utf-8 -*-

#    Copyright (C) 2014 by Promotux
#                       di Francesco Meloni snc - http://www.promotux.it/

#    Author: Francesco Meloni  <francesco@promotux.it>

#    This file is part of OdmCollect.

#    OdmCollect is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 2 of the License, or
#    (at your option) any later version.

#    OdmCollect is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.

#    You should have received a copy of the GNU General Public License
#    along with OdmCollect.  If not, see <http://www.gnu.org/licenses/>.

import os
import sys
from werkzeug import SharedDataMiddleware, ClosingIterator
from werkzeug.exceptions import HTTPException, NotFound
from werkzeug import Local, LocalManager
import Environment
import preEnv
from web_lib.webutils import *
from web_lib import routes
from inspect import *
from web_lib.page import Page
from werkzeug import Local, LocalManager, cached_property

local = Local()
local_manager = LocalManager([local])
application = local('application')

class PgWebGeneric(object):

    def __init__(self, path=None):
        local.application = self
        try:
            if not (os.path.exists("cache")):
                    os.mkdir("cache")
            if not (os.path.exists("session")):
                    os.mkdir("session")
        except:
            print("pazienza")

        #TODO: eventuale gestione modulare successiva come nel pg
        #self.importModulesFromDir(modules_dir="./promogest/pages/modules")
        #Aggiungo le directory di lavoro ...
        STATIC_PATH = Environment.STATIC_PATH
        if not os.path.exists(STATIC_PATH):
            STATIC_PATH= "/home/promo/odmc/tpl"
        if preEnv.wsgi == False:
            self.dispatch = SharedDataMiddleware(self.dispatch, {
            '/tpl/': STATIC_PATH
        })

    def dispatch(self, environ, start_response):
        """ Funzione importante per la gestione dello smistamento della request

        """
        local.application = self
        req = Request(environ)
        Environment.req = req
        local.url_adapter = adapter = url_map.bind_to_environ(environ)
        try:
            endpoint, values = adapter.match()
            #print " ENDPOINT", endpoint , values
            handler = getattr(routes, endpoint)
            jinja_env.globals['req'] = req
            pathList = req.path.split('/')
            jinja_env.globals['path'] = pathList
            #print "PATHLIST", pathList, handler
            #print getmembers(handler)
            #print getvars(handler)
            #print "req.path --->", req.path
            #print "req.script_root --->", req.script_root
            #print "req.url --->", req.url
            #print "req.base_url --->", req.base_url
            #print "req.url_root --->", req.url_root
            #print "req.host_url --->", req.host_url
            #print "req.host --->", req.host_url
            #print "req.remote_addr --->", req.remote_addr
            #print "pathList --->", pathList
            response = handler(req, **values)
        except NotFound, e:
            response = self.not_found(req)
            response.status_code = 404
        except HTTPException, e:
            response = e
        Environment.session.close()
        return ClosingIterator(response(environ, start_response),
                               [local_manager.cleanup])

    def __call__(self, environ, start_response):
        #Environment.conn.close()
        return self.dispatch(environ, start_response)

    def not_found(self,req):
        pageData = {'file' : '/main/not_found'}
        return Page(req).render(pageData)
